package cn.neo.hhrpc.core.cluster;

import cn.neo.hhrpc.core.api.LoadBalancer;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRibbonLoadBalancer<T> implements LoadBalancer<T> {

    AtomicInteger index = new AtomicInteger(0);

    @Override
    public T choose(List<T> providers) {
        if (providers == null || providers.size() == 0) return null;
        // 这种边界优化可写可不写，略微提升性能
        if (providers.size() == 1) return providers.get(0);
        // 随机返回
//        increment会超过上限
//        return providers.get(index.getAndIncrement() % providers.size());
        return providers.get((index.getAndIncrement()&0x7fffffff) % providers.size());
    }
}
